<?php

require_once 'ActionFramework/start.php';

/**
 * 
 */
class ListField extends DoubleTagFormInput {
	
	private $is_unit_value_json;
	
	public function __construct($claimed_input, FormInput $unit_field, $is_unit_value_json=false) {
		// Set $is_unit_value_json to true if the unit-field contains json string
		// The hidden field stores json output. Change to textfield for inspection
		parent::__construct($unit_field, new HiddenField($claimed_input), 'unit', 'output');
		$this->is_unit_value_json = $is_unit_value_json;
		
		$id = $this->get_id();		
		$list_view_id = "view_$id"; 
		
		// Reorder components: view, unit field, add button
		unset($this->c['unit']);
		$this->add('view', "
			<div id='$list_view_id'></div>
		");
		// Re-insert unit field
		$this->add('unit', $this->get_visible());
		// Insert the add button
		$this->add('add_button', "
			<button onclick='list_widget_$id.add_trigger(); return false;'>+</button>
		");
		
		
		// Template shortcuts
		
		$unit_getter = $unit_field->get_js_getter();
		// TODO: FormUnit Doesn't guaranty presence of this method! => Inventariseer noden voor nieuwe interfaces
		$unit_setter = $unit_field->get_js_setter();
		// Drop-down lists have a text representation different from the actual value
		$unit_user_value_getter = (method_exists($unit_field, 'get_js_user_value_getter'))? 
									$unit_field->get_js_user_value_getter() : 
									$unit_getter;
		// If the unit value is json, it is processed as json rather than as a string
		$process = ($is_unit_value_json)? 'JSON.parse': '';
		$output_setter = $this->get_main()->get_js_setter();
		
		$this->add('script', new JavascriptBlock("
			
				var list_widget_class_$id = function() {

					var content = [];
					
					function add_trigger() {
						if (!$unit_getter()) {
							return;
						}
						_read_entry_and_add_to_content();
						refresh();
					}
					
					function _read_entry_and_add_to_content() {
						content.push({
							'value': $process($unit_getter()), 
							'text': $unit_user_value_getter()
						});
					}
					
					function remove_entry(index) {
						content.splice(index, 1);
						refresh();
					}
					
					function refresh() {
				
						var view = $('#$list_view_id');
						view.empty();
						
						if (content.length > 0) {
							jQuery.each(content, function (index, entry) {							
								var container = $('<div>'); view.append(container);
								
								var item = $('<span>'); container.append(item);
								item.text(entry.text);
								
								var remove_item = $('<button>'); container.append(remove_item);
								remove_item.text('x');
								remove_item.click(function(){ remove_entry(index); });
								
							});
						}
						else {
							view.text('(Use the + button to add items)');
						}
						
						$unit_setter('');
						
						var values = [];
						jQuery.each(content, function (index, entry) {
							values.push(entry.value);
						});
						$output_setter(JSON.stringify(values));
						
					}
					
					function onkeydown(event) {
				        // If enter is pressed, add the new value and return false (otherwise 
				        // the form will be submitted)
				        if (event.keyCode == 13) {
				            add_trigger();
				            return false;
				        }
				        return true;
				    }
					
					return {
						add_trigger: add_trigger, 
						onkeydown: onkeydown,
						_read_entry_and_add_to_content: _read_entry_and_add_to_content,
						refresh: refresh
					}
				
				}
				
				var list_widget_$id = new list_widget_class_$id();
				list_widget_$id.refresh();
				
		"));
		
	 	$this->wrap_in_div();
		
		// Add "add on enter" functionality, if the unit field supports it.
		if (method_exists($unit_field, 'set_attr')) {
			$unit_field->set_attr('onkeydown', "return list_widget_$id.onkeydown(event)"); 
		}
	}
	
	/**
	 * $value must be an array of json-able stuff
	 */
	public function set_initial_value($data) {		
		
		$id = $this->get_id();
		$data = json_encode($data);
		$unit_setter = $this->get_visible()->get_js_setter();
		
		$this->c['script']->add_code("
			jQuery(function() {
				var data = $data;
				jQuery.each(data, function(index, entry) {
					/*$unit_setter(typeof(entry) === 'string'? entry: JSON.stringify(entry));*/
					$unit_setter(entry);
					list_widget_$id._read_entry_and_add_to_content();
				});
				list_widget_$id.refresh();
			}); 
		");
	}
	
}